package com.zigin.healthcard.controller;

import com.alibaba.fastjson.JSONObject;
import com.tencent.healthcard.model.HealthCardInfo;
import com.zigin.healthcard.service.HealthCardService;
import com.zigin.healthcard.util.Base64ImageUtil;
import com.zigin.healthcard.util.Constant;
import com.zigin.healthcard.vo.HealthCardInfoVo;
import com.zigin.healthcard.vo.JsonForResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.zigin.commons.util.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "健康卡接口")
@RestController
@RequestMapping("/healthCard")
public class HealthCardController extends BaseController {

    @Autowired
    HealthCardService healthCardService;


    /**
     * @return 参数名称    参数代码	必选	类型	说明
     * 接口调用凭证	appToken	是	string	其他所有接口的调用凭证
     * 凭证有效时间	expiresIn	是	int	appToken有效时间，默认为7200秒
     */
    @GetMapping("/getAppToken")
    @ApiOperation("健康卡-获取token")
    public JsonForResult getAppToken() {
        JsonForResult jsonForResult = new JsonForResult();
        try {
            JSONObject commonOut = healthCardService.getAppToken().getJSONObject("commonOut");
            boolean b = "success".equals(commonOut.getString("errMsg")) ? true : false;
            jsonForResult.setSuccess(b);
            JSONObject rsp = healthCardService.getAppToken().getJSONObject("rsp");
            Map<String, String> obj = new HashMap<String, String>();
            obj.put("appToken", rsp.getString("appToken"));
            jsonForResult.setMessage(commonOut.getString("errMsg"));
            jsonForResult.setData(obj);
        } catch (RuntimeException e) {
            jsonForResult.setSuccess(false);
            jsonForResult.setMessage(e.getLocalizedMessage());
        } catch (Exception e) {
            jsonForResult.setSuccess(false);
            jsonForResult.setMessage(Constant.DEFAULT_MESSAGE);
            logger.error(e.getLocalizedMessage());
        }
        return jsonForResult;
    }

    /**
     * 新用户注册时，身份证上传
     *
     * @param appToken           接口调用凭证
     * @param uploadImageContent （前端要转换成字符串）
     * @return 身份证信息
     */
    @ApiOperation("健康卡-身份证上传后获取身份证显示信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appToken", value = "接口调用凭证", required = true),
            @ApiImplicitParam(name = "uploadImageContent", value = "图片转换为base64", required = true)
    })
    @PostMapping("/uploadImageContent")
    public String uploadImageContent(String appToken, String uploadImageContent) {
        //uploadImageContent= Base64ImageUtil.GetImageStr(uploadImageContent);
        return healthCardService.toOcr(appToken, uploadImageContent).toString();
    }

    /**
     * 通过健康卡授权码获取健康卡 接口
     *
     * @param appToken   接口调用凭证
     * @param healthCode 健康码
     * @return
     */
    @ApiOperation("健康卡-健康卡授权码获取健康卡")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appToken", value = "接口调用凭证", required = true),
            @ApiImplicitParam(name = "healthCode", value = "健康码", required = true)
    })
    @PostMapping("/getHealthCardByHealthCode")
    public String getHealthCardByHealthCode(String appToken, String healthCode) {
        return healthCardService.getHealthCardByHealthCode(appToken, healthCode).toString();
    }

    /**
     * 先调用getAppToken()获取接口调用凭证appToken接口获取并缓存appToken（有效期7200S）。
     * 一张健康卡只能被三个微信注册，首次注册会绑定健康卡和微信的关系，第二次、第三次注册则不会。
     * 微信身份码wechatCode有效期为30分钟且只能使用一次，注册成功时立即失效，注册失败（如核身失败）时，wechatCode不会失效，用户可继续修改信息注册。
     * 新用户注册
     *
     * @param healthCardInfo
     * @return
     */
    @ApiOperation("健康卡-新用户注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appToken", value = "接口调用凭证", required = true),
            @ApiImplicitParam(name = "healthCardInfo", value = "新用户注册信息", required = true)
    })
    @PostMapping("/newRegister")
    public String newRegister(String appToken, HealthCardInfoVo healthCardInfo) {
        JsonForResult jsonForResult = new JsonForResult();
        JSONObject commonOut = healthCardService.register(appToken, healthCardInfo).getJSONObject("commonOut");
        boolean b = "success".equals(commonOut.getString("errMsg")) ? true : false;
        return healthCardService.register(appToken, healthCardInfo).toString();
    }


    /**
     * 健康码的获取方法：
     * (1) ISV跳转开放平台URLhttps://health.tengmed.com/open/getHealthCardList?hospitalId=${hospitalId}&redirect_uri=${redirect_uri} , 其中hospitalId为开放平台分配的医院ID，redirect_uri为回跳页面，包含 https:// 或 http:// 前缀，且必须要对${redirect_uri}编码；
     * (2) 用户第一次访问时，需确认授权拉取健康卡信息，用户授权后可以访问健康卡列表页；
     * (3) 用户选择一张健康卡后，自动跳转到${redirect_uri}页面，并在路径中回传healthCode参数，通过query string可直接获取健康卡授权码healthCode
     * 1、获取方式见 【跨院用户一键注册健康卡】获取用户健康卡授权码healthCode；
     * 2、ISV必须判断：当healthCode=0时（即用户点击添加健康卡按钮），跳转到新用户建卡页面；3、ISV必须判断：当healthCode=-1时（即用户点击暂不授权按钮），跳转到上一个页面；
     *
     * @param appToken   凭证
     * @param healthCode 健康码
     * @return 参数名称    参数代码	必选	类型	说明
     * 健康卡数据	card	是	obj	json结构体，内容如下
     * 二维码文本	qrCodeText	是	string	动态二维码或静态二维码
     * 姓名	name	是	string
     * 性别	gender	是	string	男、女
     * 民族	nation	是	string	汉族、满族等
     * 出生年月日	birthday	否	string	格式：yyyy-MM-dd
     * 证件号码	idNumber	是	string
     * 证件类型	idType	是	string	01-居民身份证，其他参考证件类型表
     * 地址	address	否	string
     * 联系方式1	phone1	是	string
     * 联系方式2	phone2	否	string
     * 主索引	phid	是	string
     * 院内ID	patid	否	string	院内用户唯一标识，根据commonIn的hospitalId返回
     * 健康卡ID	healthCardId	否	string
     * 扩展字段	adminExt	是	string	返回卡管查询接口响应包的全部内容
     */
    @PostMapping("/healthCode")
    public String healthCode(String appToken, String healthCode) {
        return healthCardService.healthCode(appToken, healthCode).toString();
    }


    /**
     * 统一卡包流程
     *
     * @param appToken 接口调用凭证
     * @return 身份证信息
     * @Param qrCodeText 前端二维码字符串形式
     */
    @ApiOperation("健康卡-统一卡包")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appToken", value = "接口调用凭证", required = true),
            @ApiImplicitParam(name = "qrCodeText", value = "前端二维码String", required = true)
    })
    @PostMapping("/getOrderId")
    public JsonForResult getOrderId(String appToken, String qrCodeText) {
        JsonForResult jsonForResult = new JsonForResult();
        try {
            JSONObject commonOut = healthCardService.getOrderId(appToken, qrCodeText).getJSONObject("commonOut");
            boolean b = "success".equals(commonOut.getString("errMsg")) ? true : false;
            jsonForResult.setSuccess(b);
            String orderId = healthCardService.getOrderId(appToken, qrCodeText).toString();
            Map<String, String> obj = new HashMap<String, String>();
            String url = "https://health.tengmed.com/open/takeMsCard?order_id=" + orderId + "&redirect_uri=" + "back";
            obj.put("orderId", orderId);
            obj.put("url", url);
            jsonForResult.setMessage(commonOut.getString("errMsg"));
            jsonForResult.setData(obj);
        } catch (RuntimeException e) {
            jsonForResult.setSuccess(false);
            jsonForResult.setMessage(e.getLocalizedMessage());
        }catch (Exception e){
            jsonForResult.setSuccess(false);
            jsonForResult.setMessage(Constant.DEFAULT_MESSAGE);
            logger.error(e.getLocalizedMessage());
        }

        return jsonForResult;
//		String getOrderId = healthCardService.getOrderId(appToken, qrCodeText).toString();
//		ModelAndView mv = new ModelAndView("https://health.tengmed.com/open/takeMsCard?order_id="+getOrderId+"&redirect_uri="+"back");
//		return mv;
    }


    /**
     * 线上用卡数据监测
     *
     */
    @ApiOperation("线上用卡数据监测")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appToken", value = "接口调用凭证", required = true),
            @ApiImplicitParam(name = "HealthCardInfoVo", value = "用户信息", required = true),
            @ApiImplicitParam(name = "scene", value = "用卡环节", required =false),
            @ApiImplicitParam(name = "department", value = "用卡科室", required =false),
            @ApiImplicitParam(name = "cardChannel", value = "用卡渠道", required =false),
            @ApiImplicitParam(name = "cardCostTypes", value = "用卡费别", required =false)
    })
    @PostMapping("/On_lineReportHISData")
    public String On_lineReportHISData (String appToken,HealthCardInfoVo healthCardInfoVo,String scene,String department,String cardChannel,String cardCostTypes) {
        JsonForResult jsonForResult = new JsonForResult();
        JSONObject reportHISData = healthCardService.On_lineReportHISData(appToken, healthCardInfoVo, scene, department, cardChannel, cardCostTypes);
        boolean b = "success".equals(reportHISData.getString("errMsg")) ? true : false;
        return healthCardService.On_lineReportHISData(appToken, healthCardInfoVo, scene, department, cardChannel, cardCostTypes).toString();
    }


    /**
     * 用卡数据监测
     *
     */
    @ApiOperation("线下用卡数据监测")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appToken", value = "接口调用凭证", required = true),
            @ApiImplicitParam(name = "HealthCardInfoVo", value = "用户信息", required = true),
            @ApiImplicitParam(name = "scene", value = "用卡环节", required =false),
            @ApiImplicitParam(name = "department", value = "用卡科室", required =false),
            @ApiImplicitParam(name = "cardChannel", value = "用卡渠道", required =false),
            @ApiImplicitParam(name = "cardCostTypes", value = "用卡费别", required =false)
    })
    @PostMapping("/Under_lineReportHISData")
    public String Under_lineReportHISData (String appToken,HealthCardInfoVo healthCardInfoVo,String scene,String department,String cardChannel,String cardCostTypes) {
        JsonForResult jsonForResult = new JsonForResult();
        JSONObject reportHISData = healthCardService.On_lineReportHISData(appToken, healthCardInfoVo, scene, department, cardChannel, cardCostTypes);
        boolean b = "success".equals(reportHISData.getString("errMsg")) ? true : false;
        return healthCardService.On_lineReportHISData(appToken, healthCardInfoVo, scene, department, cardChannel, cardCostTypes).toString();
    }

}
